<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Markdown Preview</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
  <link rel="stylesheet" href="libs/bootstrap/5.1.1/bootstrap.min.css">
  <!--markdown preview-->
  <link rel="stylesheet" href="libs/markdown-it/plugins/highlightjs/atom-one-light.css">
  <link rel="stylesheet" href="libs/markdown-it/style/markdown.css">

  <!-- home -->
  <link rel="stylesheet" href="style/home.css">
</head>

<body>
<div class="markdown-preview">

  <div class="mdp__nav" id="mdpNav">
  </div>
  <div id="preview" class="mdp__view"></div>
</div>

<script src="libs/jquery/jquery.min.js"></script>
<script src="libs/bootstrap/5.1.1/bootstrap.min.js"></script>
<!-- markdown -->
<script src="libs/markdown-it/markdown-it.min.js"></script>
<script src="libs/markdown-it/plugins/highlightjs/highlight.min.js"></script>
<script src="libs/markdown-it/plugins/markdown-it-container/dist/markdown-it-container.min.js"></script>
<script src="libs/markdown-it/plugins/markdown-it-anchor/dist/markdownItAnchor.umd.js"></script>
<script src="libs/markdown-it/plugins/markdown-it-toc-done-right/markdownItTocDoneRight.umd.js"></script>
<script src="libs/markdown-it/plugins/markdown-it-emoji/dist/markdown-it-emoji.js"></script>
<script src="libs/markdown-it/plugins/markdown-it-task-checkbox/markdown-it-task-checkbox.js"></script>
<script src="libs/markdown-it/plugins/markdown-it-mathjax/markdown-it-mathjax.js"></script>
<script src="libs/markdown-it/plugins/markdownlint/markdownlint-browser.min.js"></script>
<script src="libs/markdown-it/plugins/markdownlint/markdownlint-rule-helpers-browser.min.js"></script>
<script src="libs/markdown-it/rules/rules.js"></script>
<script src="libs/markdown-it/plugins/plugins.js"></script>
<script>
$(function () {
  var dataUrl = getUrlParam("url");
  dataUrl = !!dataUrl ? dataUrl : 'docs/README.md';
  renderMarkdown(dataUrl);
  $.get('js/data/docs.json', function (data) {
    let navEl = $('#mdpNav');
    navEl.empty();
    let expandDir = [
      'docs/hsq',
    ];
    let makeul = function(hierarchy, classname){
      var dirs = hierarchy || [];//Object.keys(hierarchy);
      var ul = '<ul';
      if(classname){
        ul += ' class="' + classname + '"';
      }
      ul += '>\n';
      dirs = dirs.sort(function (a, b) {
        if (a.type > b.type) return -1;
        if (a.type < b.type) return 1;
        return 0;
      });
      dirs.forEach(function(dir){
        let path = dir.path;//hierarchy[dir].path;
        let type = dir.type;
        let isFile = type !== "directory";
        let title = dir.name.replace(dir.extension, '');
        if(isFile){ // file
          let titleEl = `
            <div class="mdp__menus-item--title d-flex align-items-center flex-fill" data-url="${path}" data-type="${type}">
              <span class="text-truncate" style="padding-left: 14px" >${title}</span>
            </div>
          `;
          ul += `<li class="mdp__menus-item-submenus" data-type="file">${titleEl}</li>\n`;
        }else{
          let arrowCls = '<i class="bi bi-chevron-right""></i>';
          let expand = expandDir.includes(path);
          if (expand)  {
            arrowCls = '<i class="bi bi-chevron-down"></i>'
          }
          let titleEl = `
            <div class="mdp__menus-item--title d-flex align-items-center" data-url="${path}"  data-type="${type}">
              ${arrowCls}
              <span class="">${title}</span>
            </div>
          `;
          ul += ` <li class="mdp__menus-item" >${titleEl}\n`;
          ul += makeul(dir.children, 'mdp__menus-submenus');
          ul += '</li>\n';
        }
      });
      ul += '</ul>\n';
      return ul;
    };

    let result = makeul(data.children, 'mdp__menus');
    navEl.append(result);

    let menusItemTitleEl = $('.mdp__menus-item--title');
    $('.bi-chevron-right').parent().next('.mdp__menus-submenus').toggle();

    $('.mdp__menus-item-submenus').click(function () {
      $('.mdp__menus-item-submenus').removeClass('mdp__menus-item__active');
      $(this).addClass('mdp__menus-item__active')
    });

    menusItemTitleEl.click(function () {
      var url = $(this).data('url');
      var type = $(this).data('type');

      if (type !== 'file') {
        expandDirByPath(url, type);
        return;
      }
      updateUrl('url', url);
      renderMarkdown(url, type);
    });
  })
});

function renderMarkdown(url) {
  $.get(url, function (data) {
    let selectorMarkdown = $('#preview');
    selectorMarkdown.empty();
    let md = window.markdownit({
      breaks: true,
      html: true,
      linkify: true,
      typographer:  true,
      highlight: function(str, lang) {
        if (!(lang && hljs.getLanguage(lang))) {
          return '';
        }

        return hljs.highlight(lang, str, true).value;
      },
      // 新增自定义配置
      lint: true,       // 是否对markdown文件进行lint
      wrapper: 'div',
      wrapperClass: 'markdown__view',
      assetsPublicPath: function (src) {
        const relativeToAbsolutePath = function relativeToAbsolutePath(base, relative) {
          const stack = base.split("/"), parts = relative.split("/");
          for (let i = 0; i < parts.length; i++) {
            if (parts[i] === ".")
              continue;
            if (parts[i] === "..")
              stack.pop();
            else
              stack.push(parts[i]);
          }
          return stack.join("/");
        };

        const regxPath = /^https?:\/\//i;
        if (!regxPath.test(src)) {
          return relativeToAbsolutePath(`${location.protocol}//${location.host}/markdown-preview/docs/hsq/`, src);
        }
        return src;
      },
    });

    markdownItRules.overWriteAllRules(md);
    markdownItPlugins.loadPlugins(md);
    selectorMarkdown.append(md.render(data));
    setTimeout(function () {
      expandDirByPath(url, 'file')
    })
  })
}

function expandDirByPath(path, type) {
  let titleEl,submenus;
  let isFile = type === 'file';
  if (!isFile) {
    titleEl = $(`[data-url="${path}"]`);
    submenus = titleEl.next('.mdp__menus-submenus')
  } else {
    titleEl = $(`[data-url="${path}"]`).parent();
    submenus = titleEl.parent('.mdp__menus-submenus')
  }

  titleEl.addClass('mdp__menus-item__active');
  let isDisplay = $(submenus).css('display') === 'block';
  if (!(isFile && isDisplay)) {
    submenus.toggle();
    let iconEl = $(submenus.prev()).find('.bi');
    if (iconEl.hasClass('bi-chevron-right')) {
      iconEl.removeClass('bi-chevron-right').addClass('bi-chevron-down');
    } else if (iconEl.hasClass('bi-chevron-down')) {
      iconEl.removeClass('bi-chevron-down').addClass('bi-chevron-right');
    }
  }
}

function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

function updateUrl(key, value) {
  var newUrl = updateQueryStringParameter(window.location.href, key, value);
  window.history.replaceState({
    path: newUrl
  }, '', newUrl);
}

function updateQueryStringParameter(uri, key, value) {
  if(!value) {
    return uri;
  }
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}
</script>
</body>

</html>
